`include "defines.svh"

module regfile (
    input wire                  clk,
    input wire                  rst,


    input wire                  wen,
    input wire[4:0]             waddr,
    input wire[31:0]            wdata,


    input wire                  en1,
    input wire[4:0]             raddr1,
    output reg[31:0]            rdata1,

    input wire                  en2,
    input wire[4:0]             raddr2,
    output reg[31:0]            rdata2
);

reg[31:0] regs[0:31];

//写入：时序逻辑
//读取：组合逻辑

integer i;
always @(posedge clk) begin
    if(rst == `ON) begin
        for(i = 0;i < 32; i = i + 1) begin
            regs[i] <= `NULL;
        end
    end
    else begin
        if(wen == `ON && waddr != 5'b00000) begin
            regs[waddr] <= wdata;
        end
    end
end

always @(*) begin
    if(rst == `ON) begin
        rdata1 = `NULL;
        rdata2 = `NULL;
    end
    else begin
        if(en1 == `ON) begin
            if(raddr1 == 5'b00000) begin
                rdata1 = `NULL;
            end else if(raddr1 == waddr && wen == `ON) begin
                rdata1 = wdata;    //处理数据冒险
            end else begin
                rdata1 = regs[raddr1];
            end
        end else begin
            rdata1 = `NULL;
        end

        if(en2 == `ON) begin
            if(raddr2 == 5'b00000) begin
                rdata2 = `NULL;
            end else if(raddr2 == waddr && wen == `ON) begin
                rdata2 = wdata;    //处理数据冒险
            end else begin
                rdata2 = regs[raddr2];
            end
        end else begin
            rdata2 = `NULL;
        end

    end
end

endmodule
